package org.example.binaryTree;

import java.util.LinkedList;

public class IsCBT {

    /**
     * 是否为完全二叉树
     */
    public static boolean checkCBT(Node head) {
        if (head == null) {
            return  true;
        }
        boolean leaf = false;
        LinkedList<Node> queue = new LinkedList<>();
        Node l = null;
        Node r = null;
        queue.add(head);
        while (!queue.isEmpty()){
            head = queue.poll();
            l = head.left;
            r = head.right;
            if(
                    (l == null && r != null)
                    || (leaf && (l != null || r != null))
            ) {
                return false;
            }
            if (l != null) {
                queue.add(l);
            }
            if(r != null) {
                queue.add(r);
            }
            if( l == null || r == null) {
                leaf = true;
            }
        }
        return  true;
    }

    public static void main(String[] args) {
        Node node1 = new Node(7);
        Node node2 = new Node(4);
        Node node3 = new Node(8);
        Node node4 = new Node(3);
        Node node5 = new Node(5);
        Node node6 = new Node(7);
        Node node7 = new Node(9);


        node1.left = node2;
        node1.right = node3;
        node2.right = node4;
        node2.left = node5;
        node3.left = node6;
        node3.right = node7;


        System.out.println(checkCBT(node1));
    }
}
